package com.pn.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.pn.entity.Client;

import com.pn.mapper.ClientMapper;
import com.pn.service.ClientService;
import com.pn.utils.PageBean;
import com.pn.utils.Result;
import com.pn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ClientServiceImpl implements ClientService {
    @Autowired
    private ClientMapper clientMapper;

    //显示客户信息
    @Override
    public PageBean clietPageList(Client client) {
        PageHelper.startPage(client.getPageNum(),client.getPageSize());
        Page<Client> page = clientMapper.clientPageList(client);
        return new PageBean(page.getTotal(),page.getResult());
    }

    //修改客户
    @Override
    public Result clientUpdate(Client client) {
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        client.setUpdateBy(userId);
        client.setUpdateTime(LocalDateTime.now());

        int i = clientMapper.clientUpdate(client);
        if (i > 0 ){
            return Result.ok("修改客户成功");
        }

        return Result.err(Result.CODE_ERR_BUSINESS,"修改客户失败");
    }

    //添加客户
    @Override
    public Result clientAdd(Client client) {
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        client.setCreateBy(userId);
        client.setCreateTime(LocalDateTime.now());
        client.setIsDelete(0);
        int i = clientMapper.clientInsert(client);
        if (i > 0 ){
            return Result.ok("添加客户成功");
        }

        return Result.err(Result.CODE_ERR_BUSINESS,"添加客户失败");
    }

    //删除客户
    @Override
    public Result clientDelete(Integer clientId) {
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        Client client = new Client();
        client.setClientId(clientId);
        client.setUpdateBy(userId);
        client.setUpdateTime(LocalDateTime.now());

        int i = clientMapper.clientDelete(client);
        if (i > 0 ){
            return Result.ok("删除客户成功");
        }

        return Result.err(Result.CODE_ERR_BUSINESS,"删除客户失败");
    }

    //显示客户表
    @Override
    public List<Client> clietList() {
       List<Client> clientList =  clientMapper.clientList();
        return clientList;
    }
}
